<script lang="ts" setup>
const showViewer = ref(false),
  fileList = ref([]);

const imgRef = ref();
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
  },
  size: {
    type: Object,
  },
});

const emits = defineEmits(["update:modelValue", "change"]);

const success = (value: any) => {
  emits("update:modelValue", value.url);
  emits("change", value.url);
  if (props.size) {
    nextTick(() => {
      setTimeout(() => {
        let img = imgRef.value.$el.querySelector("img");
        let height = parseInt(
          ((Number(props.size.width) / Number(img.naturalWidth)) *
            img.naturalHeight) as any
        );
        emits("change", value.url, { width: props.size.width, height });
      }, 1000);
    });
  }
};

const previewImg = () => {
  showViewer.value = true;
};

const deleteImg = () => {
  emits("update:modelValue", "");
  emits("change", "");
};
</script>
<template>
  <div class="img">
    <el-image
      v-if="modelValue"
      ref="imgRef"
      style="width: 100%; height: 100%"
      :src="modelValue"
      fit="contain"
    ></el-image>
    <div class="upload-img_cover">
      <el-button size="small" @click.stop="previewImg">放大</el-button>
      <Upload
        :model-value="fileList"
        :limit="999"
        :show-file-list="false"
        @success="success"
      >
        <el-button size="small">替换</el-button>
      </Upload>
      <el-button
        size="small"
        @click.stop="deleteImg"
        v-if="$route.query.from === 'sass'"
        >删除</el-button
      >
    </div>
  </div>
  <el-image-viewer
    v-if="showViewer"
    :initial-index="0"
    :url-list="[modelValue]"
    @close="showViewer = false"
  >
  </el-image-viewer>
</template>
<style lang="scss" scoped>
.img {
  width: 124px;
  height: 124px;
  position: relative;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
  background-position: 0 0, 15px 15px;
  background-size: 10px 10px;
  background-image: linear-gradient(
      45deg,
      #ccc 25%,
      transparent 0,
      transparent 75%,
      #ccc 0
    ),
    linear-gradient(45deg, #ccc 25%, transparent 0, transparent 75%, #ccc 0);
  &:hover {
    .upload-img_cover {
      opacity: 1;
    }
  }
  .upload-img_cover {
    opacity: 0;
    position: absolute;
    transition: all 0.3s ease;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
  }
}
</style>
